<?php

namespace App\Models;

use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use Dcat\Admin\Form;
use Dcat\Admin\Grid\Model;
use Dcat\Admin\Repositories\Repository;
use Exception;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Support\Collection;

class Cdn extends Repository
{
    protected string $keyName = 'DomainName';

    /**
     * @throws ClientException
     */
    public static function initAliyun(Aliyun $aliyun): string
    {
        $aliyun->initClient();

        return self::class;
    }

    public function store(Form $form): bool
    {
        $attributes = $form->updates();
        try {
            $sources = [
                [
                    'content' => $attributes['content'],
                    'type' => 'oss',
                    'priority' => '20',
                    'port' => 80,
                    'weight' => 100,
                ],
            ];
            $host = $attributes['host'].'.'.$attributes['domain'];

            \AlibabaCloud\Cdn\Cdn::v20180510()
                ->addCdnDomain()
                ->withDomainName($host)
                ->withCdnType('web')
                ->withSources(json_encode($sources))
                ->request();

            return true;
        } catch (Exception) {
            return false;
        }
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function edit(Form $form): array|Arrayable
    {
        $id = $form->builder()->getResourceId();

        return \AlibabaCloud\Cdn\Cdn::v20180510()
            ->describeCdnDomainDetail()
            ->withDomainName($id)
            ->request()
            ->get('GetDomainDetailModel');
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function get(Model $model): array|Collection|LengthAwarePaginator
    {
        $currentPage = $model->getCurrentPage();
        $perPage = $model->getPerPage();

        $res = \AlibabaCloud\Cdn\Cdn::v20180510()
            ->describeUserDomains()
            ->withPageSize($perPage)
            ->withPageNumber($currentPage)
            ->request();

        return $model->makePaginator(
            $res->get('TotalCount'),
            $res->get('Domains.PageData')
        );
    }

    public function update(Form $form): bool
    {
        try {
            $id = $form->builder()->getResourceId();
            $attributes = $form->updates();
            $sources = [
                [
                    'content' => $attributes['content'],
                    'type' => 'oss',
                    'priority' => '20',
                    'port' => 80,
                    'weight' => 100,
                ],
            ];

            \AlibabaCloud\Cdn\Cdn::v20180510()
                ->modifyCdnDomain()
                ->withDomainName($id)
                ->withSources(json_encode($sources))
                ->request();

            return true;
        } catch (Exception) {
            return false;
        }
    }

    public function deleting(Form $form): array
    {
        return [];
    }

    /**
     * @throws ClientException
     * @throws ServerException
     */
    public function delete(Form $form, array $deletingData): bool
    {
        $ids = $form->builder()->getResourceId();
        $ids = explode(',', $ids);

        foreach ($ids as $id) {
            \AlibabaCloud\Cdn\Cdn::v20180510()
                ->deleteCdnDomain()
                ->withDomainName($id)
                ->request();
        }

        return true;
    }
}
